package com.example.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.jdbc.ScriptRunner;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.Reader;
import java.io.StringWriter;
import java.nio.charset.StandardCharsets;

@Slf4j
public class DBUtils {
    public static final String ENV_LOCAL = "local";
    public static final String ENV_TEST = "test";
    public static final String ENV_PRO= "pro";

    private DBUtils() {

    }

    /**
     * 初始化数据库
     * @param active 初始化的环境
     */
    public static void initDB(String active) {
        try {
            //通过数据源获取数据库链接
            Reader asReader = Resources.getResourceAsReader("SqlMapConfig-" + (ENV_PRO.equals(active) ? ENV_PRO : ENV_TEST) + ".xml");
            SqlSessionFactory sessionFactory  = (new SqlSessionFactoryBuilder()).build(asReader);
            SqlSession sqlSession = sessionFactory.openSession();

            //创建脚本执行器
            ScriptRunner scriptRunner = new ScriptRunner(sqlSession.getConnection());
            //创建字符输出流，用于记录SQL执行日志
            StringWriter writer = new StringWriter();
            PrintWriter print = new PrintWriter(writer);
            //设置执行器日志输出
            scriptRunner.setLogWriter(print);
            //设置执行器错误日志输出
            scriptRunner.setErrorLogWriter(print);
            //设置读取文件格式
            Resources.setCharset(StandardCharsets.UTF_8);
            Reader reader = null;
            try {
                //获取资源文件的字符输入流
                reader = Resources.getResourceAsReader("sql/init.sql");
            } catch (IOException e) {
                //文件流获取失败，关闭链接
                log.error(e.getMessage(), e);
                scriptRunner.closeConnection();
                return;
            }
            //执行SQL脚本
            scriptRunner.runScript(reader);
            //关闭文件输入流
            try {
                reader.close();
            } catch (IOException e) {
                log.error(e.getMessage(), e);
            }
            //输出SQL执行日志
            log.debug(writer.toString());
            //关闭输入流
            scriptRunner.closeConnection();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }
}
